<?php
// +----------------------------------------------------------------------
// | 鸿运集团 [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://tplay.pengyichen.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 听雨 < 389625819@qq.com >
// +----------------------------------------------------------------------
//计算2个日期的时间差
function timediff($begin_time,$end_time)

{
	
	if($begin_time < $end_time){
		$starttime = $begin_time;
		$endtime = $end_time;
	}else{
		$starttime = $end_time;
		$endtime = $begin_time;
	}
	//计算天数
	$timediff = $endtime-$starttime;
	$days = intval($timediff/86400);
	//计算小时数
	$remain = $timediff%86400;
	$hours = intval($remain/3600);
	//计算分钟数
	$remain = $remain%3600;
	$mins = intval($remain/60);
	//计算秒数
	$secs = $remain%60;
	$res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
	return $res;

}
//日期增加天数
function add_days($data,$day){
	 return date('Y-m-d',strtotime("{$data} +$day day"));
}
/* 
 * 加密--32位密码
 */
function md5_salt($password) {
	return md5(crypt($password, config('salt')));
}
// 应用公共文件
function pay_code($app,$key,$op,$amount,$channel,$local_order_no,$notify_url='',$redirect_url=''){
	$url="http://openapi.caibaopay.com/gatewayOpen.htm?";
	$t=time();
//	$app="H48007350000002";
//	$key="ac8f09abd655bdfc0345f61ddf6d658f";
//	$op="2ec6d8240578a85b0b6949b3a335f98a";
//	$local_order_no=123456789;
	$notify_url=$notify_url?$notify_url:config("notify_url");
	$redirect_url=$redirect_url?$redirect_url:config("redirect_url")."?order_sn=$local_order_no";
//	$amount=1;
	$amount=$amount*100;
	$confirm_way="AUTO_PAY";
	$pt  ="amount=$amount&app=$app&confirm_way=$confirm_way&local_order_no=$local_order_no&operator_id=$op&timestamp=$t";
	$data="amount=$amount&app=$app&command=caibao.pay.h5&confirm_way=$confirm_way&local_order_no=$local_order_no&notify_url=$notify_url&operator_id=$op&redirect_url=$redirect_url&timestamp=$t";
	$pt.="&key=$key";
	$sign=bin2hex(md5($pt,true));//md5($pt);
	$url.=$data."&sign=$sign";
	$res=file_get_contents($url);
	$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
	$array1 = get_object_vars($jsondecode1);//转换成数组
	$result=$array1['data'];
	$result=get_object_vars($result);
	//$qrcode= 'http://www.vshop88.net/code/code.php?url='.urlencode($result['qrCode']).'&margin=1&size=10';
		//$qrcode = $qrPay->create_erweima($response->qr_code);
	//echo "<img src=$qrcode />";
	return $result['url'];
	exit;
}
//判断是微信还是支付波啊打开1支付宝2微信
	function get_brower_type(){
		if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
			return 2;
		}elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false) {
			return 1;
		}
		return 0;
	}
/**
 * 生成订单号
 */
function order_create_no(){
	$year_code = array('A', 'B', 'C', 'D', 'E', 'F');
    $date_code = array('0','1', '2', '3', '4', '5', '6', '7', '8', '9', 'A','C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M','N', 'O', 'P', 'Q', 'R', 'T', 'U', 'V', 'W', 'X', 'Y');
    //一共15位订单号,同一秒内重复概率1/10000000,26年一次的循环\
    $order_sn = $year_code[(intval(date('Y')) - 2010) % 6] . //年 1位
    strtoupper(dechex(date('m'))) . //月(16进制) 1位
    $date_code[intval(date('d'))] . //日 1位
    substr(time(), -5) . substr(microtime(), 2, 5) . //秒 5位 // 微秒 5位
    sprintf('%02d', rand(0, 99)); //  随机数 2位
    return $order_sn;
}
/**
 * 根据附件表的id返回url地址
 * @param  [type] $id [description]
 * @return [type]     [description]
 */
function geturl($id)
{
	if ($id) {
		$geturl = \think\Db::name("attachment")->where(['id' => $id])->find();
		if($geturl['status'] == 1) {
			//审核通过
			return $geturl['filepath'];
		} elseif($geturl['status'] == 0) {
			//待审核
			return '/uploads/xitong/beiyong1.jpg';
		} else {
			//不通过
			return '/uploads/xitong/beiyong2.jpg';
		} 
    }
    return false;
}


/**
 * [SendMail 邮件发送]
 * @param [type] $address  [description]
 * @param [type] $title    [description]
 * @param [type] $message  [description]
 * @param [type] $from     [description]
 * @param [type] $fromname [description]
 * @param [type] $smtp     [description]
 * @param [type] $username [description]
 * @param [type] $password [description]
 */
function SendMail($address)
{
    vendor('phpmailer.PHPMailerAutoload');
    //vendor('PHPMailer.class#PHPMailer');
    $mail = new \PHPMailer();          
     // 设置PHPMailer使用SMTP服务器发送Email
    $mail->IsSMTP();                
    // 设置邮件的字符编码，若不指定，则为'UTF-8'
    $mail->CharSet='UTF-8';         
    // 添加收件人地址，可以多次使用来添加多个收件人
    $mail->AddAddress($address); 

    $data = \think\Db::name('emailconfig')->where('email','email')->find();
            $title = $data['title'];
            $message = $data['content'];
            $from = $data['from_email'];
            $fromname = $data['from_name'];
            $smtp = $data['smtp'];
            $username = $data['username'];
            $password = $data['password'];   
    // 设置邮件正文
    $mail->Body=$message;           
    // 设置邮件头的From字段。
    $mail->From=$from;  
    // 设置发件人名字
    $mail->FromName=$fromname;  
    // 设置邮件标题
    $mail->Subject=$title;          
    // 设置SMTP服务器。
    $mail->Host=$smtp;
    // 设置为"需要验证" ThinkPHP 的config方法读取配置文件
    $mail->SMTPAuth=true;
    //设置html发送格式
    $mail->isHTML(true);           
    // 设置用户名和密码。
    $mail->Username=$username;
    $mail->Password=$password; 
    // 发送邮件。
    return($mail->Send());
}


/**
 * 阿里大鱼短信发送
 * @param [type] $appkey    [description]
 * @param [type] $secretKey [description]
 * @param [type] $type      [description]
 * @param [type] $name      [description]
 * @param [type] $param     [description]
 * @param [type] $phone     [description]
 * @param [type] $code      [description]
 * @param [type] $data      [description]
 */
function SendSms($param,$phone)
{
    // 配置信息
    import('dayu.top.TopClient');
    import('dayu.top.TopLogger');
    import('dayu.top.request.AlibabaAliqinFcSmsNumSendRequest');
    import('dayu.top.ResultSet');
    import('dayu.top.RequestCheckUtil');

    //获取短信配置
    $data = \think\Db::name('smsconfig')->where('sms','sms')->find();
            $appkey = $data['appkey'];
            $secretkey = $data['secretkey'];
            $type = $data['type'];
            $name = $data['name'];
            $code = $data['code'];
    
    $c = new \TopClient();
    $c ->appkey = $appkey;
    $c ->secretKey = $secretkey;
    
    $req = new \AlibabaAliqinFcSmsNumSendRequest();
    //公共回传参数，在“消息返回”中会透传回该参数。非必须
    $req ->setExtend("");
    //短信类型，传入值请填写normal
    $req ->setSmsType($type);
    //短信签名，传入的短信签名必须是在阿里大于“管理中心-验证码/短信通知/推广短信-配置短信签名”中的可用签名。
    $req ->setSmsFreeSignName($name);
    //短信模板变量，传参规则{"key":"value"}，key的名字须和申请模板中的变量名一致，多个变量之间以逗号隔开。
    $req ->setSmsParam($param);
    //短信接收号码。支持单个或多个手机号码，传入号码为11位手机号码，不能加0或+86。群发短信需传入多个号码，以英文逗号分隔，一次调用最多传入200个号码。
    $req ->setRecNum($phone);
    //短信模板ID，传入的模板必须是在阿里大于“管理中心-短信模板管理”中的可用模板。
    $req ->setSmsTemplateCode($code);
    //发送
    

    $resp = $c ->execute($req);
}


/**
 * 替换手机号码中间四位数字
 * @param  [type] $str [description]
 * @return [type]      [description]
 */
function hide_phone($str){
    $resstr = substr_replace($str,'****',3,4);  
    return $resstr;  
}

 /**
 * 检测sql
 * @param unknown $sql_str 语句
 * @return unknown 
 */
function inject_check($sql_str) {
	$check= preg_match('/select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/i', $sql_str);
	if($check){
		return true;
	}else{
		return false;
	}
}

/**
 * 返回格式化后的当前时间
 */
function now_time(){
	return date('Y-m-d H:i:s',time());
}

//获取用户微信基本信息
function get_userinfo($code){
		$curl="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".config('wxpay_appid')."&secret=".config('wxpay_appsercet')."&code=$code&grant_type=authorization_code";
		$weixin =  file_get_contents($curl);//通过code换取网页授权access_token
		$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
		$array = get_object_vars($jsondecode);//转换成数组
		$access_token=$array['access_token'];
		$openid = $array['openid'];//输出openid
		$data['openid']=$openid; 
		
		$url="https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
		$weixin =  file_get_contents($url);//通过code换取网页授权access_token
		$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
		$array = get_object_vars($jsondecode);//转换成数组
		$data['nick_name']=$array['nickname'];
		$data['headimgurl']=$array['headimgurl'];
		return $data;
	
}
//判断用户是否关注公众号
function is_atten($openid){
	$appid=config('wxpay_appid');
	$secret=config('wxpay_appsercet');
	$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";	
	$res=file_get_contents($url);
	$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
	$array1 = get_object_vars($jsondecode1);//转换成数组
	
	$access_token=$array1['access_token'];
	$res=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN");
	$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
	$array1 = get_object_vars($jsondecode1);//转换成数组
	if(isset($array1['nickname'])){
		return 1;
	}else{
		return 0;
	}
}

/**
 * 发送短信验证
 * $mobile 手机号
 * $template_no 模板编号(数据库主键)，注意不是模板ID
 */
function get_code($mobile){
	// 获取短信模板
	$tem_w['sms']='用户注册';
	
	$template = db("smsconfig")->where($tem_w)->find();
	// 如果是验证码类型，则生成6位验证码
	if($template['type'] == 1){
		$code = rand(100000, 999999);
		$template['content'] = str_replace('${code}', $code, $template['content']);
		$data['code'] = $code;
	}
	$msg=send_sms($template['name'],$mobile,$template['code'],'code',$code);
	
	if($msg){
		return json(["code"=>200,"msg"=>'发送成功!']); 
	}else{
		return json(["code"=>408,"msg"=>'发送失败']); 
	}
}
	
function send_sms($sign,$mobile,$tempid,$name,$value){
	$cut_time = now_time(); 
	include_once ('../extend/smsapi/smsDemo.php');
	$msg=sendMess($sign,$mobile,$tempid,$name,$value);
	if($msg->Message=="OK") {
		$data['mobile'] 	= $mobile;
		$data[$name] 		= $value;
		$data['add_time'] 	= $cut_time;
		$data['message'] 	= '发送成功';
		db('smscode')->insert($data);
		return true;
	}else{
		$data['mobile'] 	= $mobile;
		$data[$name] 		= $value;
		$data['add_time'] 	= $cut_time;
		$data['result'] 	= 0;
		$data['message'] 	= '发送失败:'.$msg->Message;
		db('smscode')->insert($data);
		$err=$msg->Message;
		return false;
    }
}

/**验证码*/
function check_sendcode($mobile, $code, $message){
	$where['mobile'] = $mobile;
	$where['code'] = $code;
	$where['message'] = '发送成功';
	$result =db('smscode')->where($where)->find();
	// 10分钟有效期
	if(time() - strtotime($result['add_time']) > 600){
		return 2;
	}
	if($code == $result['code']){
		return 1;
	}else{
		return -1;
	}
}

/**
 * 收银台会员卡支付& 核销日志
 * */
function cashier_pay_log($store_id,$user_id,$balance,$type,$order_sn,$pay_type,$message,$state,$level_id,$origin_price,$staff_id,$hx_total=0,$room_id=0){
	$credit_data = array(
		'store_id'		=> $store_id,
		'user_id'		=> $user_id,
		'balance'		=> $balance,
		'origin_price'	=> $origin_price,
		'type' 			=> $type,
		'order_sn' 		=> $order_sn,
		'pay_type' 		=> $pay_type,
		"msg"			=> $message,
		'add_time' 		=> now_time(),
		'state'			=>$state,
		'level_id'		=>$level_id,
		'staff_id'		=>$staff_id,
		'hx_total'		=>$hx_total,
		'room_id'		=>$room_id
	);
	$res= db('paylog')->insert($credit_data);
	return $res;
}
/**
 * 点餐支付日志
 * */
function dinner_log($store_id,$user_id,$balance,$type,$order_sn,$pay_type,$message,$origin_price,$staff_id,$room_id){
	$credit_data = array(
		'store_id'		=> $store_id,
		'user_id'		=> $user_id,
		'balance'		=> $balance,
		'origin_price'	=> $origin_price,
		'type' 			=> $type,
		'order_sn' 		=> $order_sn,
		'pay_type' 		=> $pay_type,
		"msg"			=> $message,
		'add_time' 		=> now_time(),
		'state'			=>2,
		'staff_id'		=>$staff_id,
		'room_id'		=>$room_id
	);
	$res= db('paylog')->insert($credit_data);
	return $res;
}
//会员卡消费&充值&核销日志日志
function card_xf_log($order_sn,$user_id,$store_id,$balance,$fill_id,$pay_type,$level_id,$time,$type,$staff_id,$msg,$num=0,$room_id=0){
	//购买日志
	$credit_data = array(
		'order_sn'		=> $order_sn,
		'user_id'		=> $user_id,
		'store_id'		=> $store_id,
		'balance'		=> $balance,
		'fill_id' 		=> $fill_id,
		'pay_type' 		=> $pay_type,
		'level_id' 		=> $level_id,
		'time' 			=> $time,
		"type"			=> $type,
		"staff_id"		=> $staff_id,
		'msg' 			=> $msg,
		'num'			=>$num,
		'room_id'		=>$room_id
	);
	$res= db('consume')->insert($credit_data);
	return $res;
}

/**
 * 会员识别码核销日志
 */
function syt_reserve_log($user_id,$store_id,$room_id,$start_time,$end_time,$room_num,$zf_type,$is_hx,$days){
	$data =array(
		'user_id'	=>$user_id,
		'store_id'	=>$store_id,
		'room_id'	=>$room_id,
		'start_time'=>$start_time,
		'end_time'	=>$end_time,
		'room_num'	=>$room_num,
		'zf_type'	=>$zf_type,
		'is_hx' 	=>$is_hx,
		'state'		=>1,
		'days'		=>$days,
		'add_time'	=>now_time(),
		'hx_time'	=>now_time()
	);
	$res = db('reserve')->insert($data);
	return $res;
}

/**
 * 交班日志
 * $emp  所有统计数据
 * */
function jiaoban_log($emp){
	$data =array(
		'emp_id'		=>$emp['emp_id'],
		'emp_name'		=>$emp['name'],
		'store_id'		=>$emp['store_id'],
		'group_id'		=>$emp['group_id'],
		'start_time'	=>$emp['login_time'],
		'end_time'		=>$emp['now_time'],
		'order_count'	=>$emp['count_order'],
		'total_order'	=>$emp['origin_price'],
		'yh_count'		=>$emp['count_yh'],
		'yh_money'		=>$emp['yh_money'],
		'sj_count'		=>$emp['count_order'],
		'sj_money'		=>$emp['balance'],
		'zfb_count'		=>$emp['zfb']['zfb_count'],
		'zfb_balance'	=>$emp['zfb']['zfb_balance'],
		'wx_count'		=>$emp['wx']['wx_count'],
		'wx_balance'	=>$emp['wx']['wx_balance'],
		'yl_count'		=>$emp['yl']['yl_count'],
		'yl_balance'	=>$emp['yl']['yl_balance'],
		'xj_count'		=>$emp['xj']['xj_count'],
		'xj_balance'	=>$emp['xj']['xj_balance'],
		'cz_count'		=>$emp['card_cz']['count_cz'],
		'cz_card'		=>$emp['card_cz']['card_cz'],
		'xf_count'		=>$emp['card_xf']['count_xf'],
		'xf_card'		=>$emp['card_xf']['card_xf'],
		'fq_count'		=>$emp['fq_zs']['count_zs'],
		'fq_zs'			=>$emp['fq_zs']['zs_num'],
		'hx_count'		=>$emp['fq_hx']['count_hx'],
		'fq_hx'			=>$emp['fq_hx']['hx_num'],
		'tk_count'		=>$emp['tk']['count_tk'],
		'tk'	=>$emp['tk']['tk']
	);
	$res = db('jiaoban')->insert($data);
	return $res;
}


/**
 * 收银台会员卡充值日志
 * */
function card_cz_log($store_id,$user_id,$balance,$type,$order_sn,$pay_type,$message,$state,$staff_id){
	$credit_data = array(
		'store_id'		=> $store_id,
		'user_id'		=> $user_id,
		'balance'		=> $balance,
		'origin_price'	=> $balance,
		'type' 			=> $type,
		'order_sn' 		=> $order_sn,
		'pay_type' 		=> $pay_type,
		'state' 		=> 1,
		"msg"		=> $message,
		"order_id"		=> 0,
		'add_time' 		=> now_time(),
		'state'			=>$state,
		'staff_id'		=>$staff_id
	);
	$res= db('paylog')->insert($credit_data);
	return $res;
}


//根据付款吗判断是微信还是支付宝
/*
 * 支付宝25~30开头的长度为16~24位的数字
 * 微信18位纯数字，以10、11、12、13、14、15开头）
 */
function get_bartype($bar){
	$begin=substr($bar,0,2);
	if($begin>20){
		return 3;
	}else{
		return 2;
	}
}

/*条码支付
 *$param $app  商户号
 * $param $key 商户 密匙
 * $op  商户收银员号
 * $amount 顶大价格
 * $channel 支付方式1支付宝2微信
 * $local_order_no 订单号
 * $notify_url="http://t1.lxtx001.com/api/index"; 回调地址
 * 
 */
function bar_pay($barcode,$app,$key,$op,$amount,$channel,$local_order_no,$notify_url='',$redirect_url=''){
	$url="http://openapi.caibaopay.com/gatewayOpen.htm?";
	$t=time();
	$notify_url=$notify_url?$notify_url:config("notify_url");
	$redirect_url=$redirect_url?$redirect_url:config("redirect_url")."?order_sn=$local_order_no";
	//$amount=1;
	$amount=$amount*100;
	$pt  ="amount=$amount&app=$app&barcode=$barcode&local_order_no=$local_order_no&operator_id=$op&timestamp=$t";
	$data="amount=$amount&app=$app&barcode=$barcode&command=open.pay.barcode&local_order_no=$local_order_no&notify_url=$notify_url&operator_id=$op&redirect_url=$redirect_url&timestamp=$t";
	$pt.="&key=$key";
	$sign=bin2hex(md5($pt,true));//md5($pt);
	$url.=$data."&sign=$sign";
	$res=file_get_contents($url);
	file_put_contents("a.txt", $res);
	$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
	$array1 = get_object_vars($jsondecode1);//转换成数组
	$result=$array1['data'];
	$result=get_object_vars($result);
	return $result['orderStatus'];
}


/**
 * $local_order_no退款订单
 */
function order_refund($local_order_no,$amount,$app,$key,$op){
	$url="http://openapi.caibaopay.com/gatewayOpen.htm?";
	$t=time();
	$local_refund_no=order_create_no();
	$refund_amount=$amount*100;
	$pt  ="app=$app&local_order_no=$local_order_no&local_refund_no=$local_refund_no&operator_id=$op&timestamp=$t";
	$data="app=$app&command=caibao.pay.refund&local_order_no=$local_order_no&local_refund_no=$local_refund_no&operator_id=$op&refund_amount=$refund_amount&timestamp=$t&version=1.0";
	$pt.="&key=$key";
	$sign=bin2hex(md5($pt,true));//md5($pt);
	$url.=$data."&sign=$sign";
	$res=file_get_contents($url);
	header("Content-type: text/html; charset=utf-8"); 
	$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
	$array1 = get_object_vars($jsondecode1);//转换成数组
	$result=$array1['data'];
	$result=get_object_vars($result);
	//$qrcode= 'http://www.vshop88.net/code/code.php?url='.urlencode($result['qrCode']).'&margin=1&size=10';
		//$qrcode = $qrPay->create_erweima($response->qr_code);
	//echo "<img src=$qrcode />";
	return $result['refundAmount'];
	exit;
}